package com.game.state;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.microedition.khronos.opengles.GL10;

import media.sound.GameSound;
import object.obj2D.graphics.Char;
import object.obj2D.graphics.TexSquare;
import object.obj2D.graphics.Texture;
import system.Device;
import system.GameOption;
import system.Graphics;
import system.KeyBoard;
import android.content.Context;

import com.game.GamePlay;
import com.game.R;

public class Complete extends State {
	private final int MENU_ITEM_BACK = 0;
	private final int MENU_ITEM_RESET = MENU_ITEM_BACK + 1;
	private final int MENU_ITEM_BEGIN = MENU_ITEM_BACK;
	private final int MENU_ITEM_END = MENU_ITEM_RESET;

	private int selected = MENU_ITEM_BEGIN;

	private GL10 gl;
	private int m_fSrcWidth;
	private int m_fSrcHeight;
	private int sNumMenuItem = 2;
	private int[] m_iMenuItemTex = new int[sNumMenuItem];
	private int[] m_iMenutemSelectedTex = new int[sNumMenuItem];
	private int m_itexBgID;
	private int m_BgID;

	private float m_fMenuItemHeight = Size.MNU_ITEM_HEIGHT;
	private float m_fMenuItemWidth = Size.MNU_ITEM_WIDTH;
	private Texture m_texture = new Texture();
	private TexSquare m_hscBg;
	private TexSquare m_hscItem;
	private int m_numOfUser;
	private int m_maxOfUser = 6;
	private int m_maxOfNumber = 10;
	private String m_fileName = "hsc.bin";
	private int[] m_iScore = new int[m_maxOfUser];
	private Context context = Device.GetContext();
	private Char strDraw = new Char();
	
	private long m_timeDisplay = 3000;
	private long m_beginTime;
	private boolean m_isActive = false;
	private int state = 0;
	private int score = 10;
	private String sScore = String.valueOf(score);

	public Complete() {
		this.ReadFile(context);
		strDraw.setiSize(45 * Device.GetScaleFactorW(), 45 * Device
				.GetScaleFactorH());
		this.UpdateHsc(12);
	}

	@Override
	public void Init() {
		gl = Graphics.GetGraphics();
		m_fSrcWidth = Device.GetWidth();
		m_fSrcHeight = Device.GetHeight();

		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		float w = m_fSrcWidth / 2;
		float h = m_fSrcHeight / 2;
		gl.glOrthof(-w, w, -h, h, -1.0f, 1.0f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glPushMatrix();
		// Load menu item texture
		m_iMenuItemTex[MENU_ITEM_BACK] = m_texture
				.initTexture(R.drawable.mnu_back);
		m_iMenutemSelectedTex[MENU_ITEM_BACK] = m_texture
				.initTexture(R.drawable.mnu_back_select);
		m_iMenuItemTex[MENU_ITEM_RESET] = m_texture
				.initTexture(R.drawable.mnu_hsc_reset);
		m_iMenutemSelectedTex[MENU_ITEM_RESET] = m_texture
				.initTexture(R.drawable.mnu_hsc_reset_select);

		m_hscItem = new TexSquare(m_fMenuItemWidth, m_fMenuItemHeight);

		// Load background texture
		m_itexBgID = m_texture.initTexture(R.drawable.mnu_hsc_bg);
		m_BgID = m_texture.initTexture(R.drawable.mainmenu_bg);
		m_hscBg = new TexSquare(Size.SCREEN_WIDTH, Size.SCREEN_HEIGHT);
	}

	@Override
	public void Update(GamePlay gamePlay) {
		
		super.Update(gamePlay);
		
		if(!m_isActive){
			m_beginTime = System.currentTimeMillis();
			m_isActive = true;
		}
		if(System.currentTimeMillis() - m_beginTime > m_timeDisplay){
			state = 1;
			strDraw.setiSize(20*Device.GetScaleFactorW(), 20*Device.GetScaleFactorH());
		}			
	}

	@Override
	public void Render() {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		if(state == 0){
			m_texture.loadTexture(m_BgID);
			m_hscBg.Render();
			strDraw.DrawString("Your score", -Device.GetWidth()/2, Device.GetHeight()/4);
			int leng = sScore.length();
			strDraw.DrawString(sScore, -strDraw.getSizeWidth()*leng/2, -Device.GetHeight()/4);
		}
		if(state == 1){
			// Back ground
			m_texture.loadTexture(m_itexBgID);
			m_hscBg.Render();

			// Draw menuItem

			for (int i = 0; i < sNumMenuItem; ++i) {
				gl.glPushMatrix();
				if (selected == i)
					m_texture.loadTexture(m_iMenutemSelectedTex[i]);
				else
					m_texture.loadTexture(m_iMenuItemTex[i]);
				gl.glTranslatef((2 * i - 1) * (m_fSrcWidth - Device.MENU_BUTTON_WIDTH) / 2,
						-(m_fSrcHeight - Device.MENU_BUTTON_HEIGHT) / 2, 0);
				m_hscItem.Render();
				gl.glPopMatrix();
			}
			for (int i = 0; i < m_numOfUser; i++) {
				float x = -m_fSrcWidth / 4;
				float y = -i * (strDraw.getSizeHeight() * 1.5f) + m_fSrcHeight / 5;
				strDraw.DrawString(String.valueOf(i + 1), x, y);
				x += 5 * strDraw.getSizeWidth();
				strDraw.DrawString(String.valueOf(m_iScore[i]), x, y);
			}
		}
	}

	@Override
	public void Destroy() {
		m_texture = null;
		m_hscItem = null;
		m_iMenuItemTex = null;
		m_iMenutemSelectedTex = null;
		m_iScore = null;
		strDraw = null;

	}

	private void UpdateHsc(int score) {
		int i, j;
		for (i = 0; i < m_maxOfUser && m_iScore[i] >= score; i++);
		if (i < m_maxOfUser) {
			m_numOfUser++;
			m_numOfUser = m_numOfUser > m_maxOfUser ? m_maxOfUser : m_numOfUser;
			for (j = m_maxOfUser - 1; j > i; j--) {
				m_iScore[j] = m_iScore[j - 1];
			}
			m_iScore[i] = score;
			WriteFile(context);
		}
	}

	private void WriteFile(Context context) {
		FileOutputStream out;
		byte[] byteBuffer;
		String str = "";
		try {
			out = context.openFileOutput(m_fileName,
					Context.MODE_WORLD_WRITEABLE);
			out.write(m_numOfUser);
			for (int i = 0; i < m_numOfUser; i++) {
				str = String.valueOf(m_iScore[i]);
				while(str.length() < m_maxOfNumber){
					str = "0" + str;
				}
				byteBuffer = str.getBytes();
				
				out.write(byteBuffer);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void ReadFile(Context context) {
		FileInputStream in;
		byte[] byteBuffer = new byte[m_maxOfNumber];
		String score;
		try {
			in = context.openFileInput(m_fileName);
			m_numOfUser = in.read();
			for (int i = 0; i < m_numOfUser; i++) {
				in.read(byteBuffer);
				score = new String(byteBuffer);
				m_iScore[i] = Integer.parseInt(score);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void ProcessKeyboard(GamePlay gamePlay) {
		// TODO Auto-generated method stub
		if (KeyBoard.IsKeyPressed(DK_PAD_RIGHT)) {
			selected++;
			if (selected > MENU_ITEM_END)
				selected = MENU_ITEM_END;
			
			if (GameOption.isSoundOn)
				GameSound.GetEffSound().PlayChangeMenu();
		} else if (KeyBoard.IsKeyPressed(DK_PAD_LEFT)) {
			selected--;
			if (selected < MENU_ITEM_BEGIN)
				selected = MENU_ITEM_BEGIN;
			
			if (GameOption.isSoundOn)
				GameSound.GetEffSound().PlayChangeMenu();
		} else if (KeyBoard.IsKeyPressed(DK_PAD_MIDDLE)) {
			switch (selected) {
			case MENU_ITEM_RESET:
				
				if (GameOption.isSoundOn)
					GameSound.GetEffSound().PlaySelectMenu();
				break;
			case MENU_ITEM_BACK:
				if (!gamePlay.ResumeState())
					gamePlay.SwitchState(GameState.MainMenu);
				
				if (GameOption.isSoundOn)
					GameSound.GetEffSound().PlaySelectMenu();
				break;
			}
		}
		KeyBoard.ClearKey();
	}
}
